package cn.ug.operation.web.controller;

import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.AplicationResourceProperties;
import cn.ug.core.SerializeObjectError;
import cn.ug.feign.MemberUserService;
import cn.ug.member.bean.response.MemberUserBean;
import cn.ug.operation.bean.CupGuessUserBean;
import cn.ug.operation.bean.CupJoinUserBean;
import cn.ug.operation.bean.GameBean;
import cn.ug.operation.mapper.entity.CupBallGame;
import cn.ug.operation.mapper.entity.CupGuessUser;
import cn.ug.operation.mapper.entity.CupJoinUser;
import cn.ug.operation.service.CupBallGameService;
import cn.ug.operation.service.CupGuessUserService;
import cn.ug.operation.service.CupJoinUserService;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static cn.ug.util.ConstantUtil.COLON;
import static cn.ug.util.ConstantUtil.DATE_FORMAT;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("game")
public class CupBallGameController {
    @Autowired
    private CupBallGameService cupBallGameService;
    @Autowired
    private CupGuessUserService cupGuessUserService;
    @Autowired
    private CupJoinUserService cupJoinUserService;
    @Autowired
    private AplicationResourceProperties properties;
    @Autowired
    private MemberUserService memberUserService;

    @GetMapping(value = "/{id}")
    public SerializeObject get(@RequestHeader String accessToken, @PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        CupBallGame entity = cupBallGameService.getGame(id);
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @GetMapping(value = "/statistics")
    public SerializeObject statistics(@RequestHeader String accessToken) {
        return new SerializeObject<>(ResultType.NORMAL, cupBallGameService.statisticsGame());
    }

    @GetMapping(value = "/gold")
    public SerializeObject statistics() {
        return new SerializeObject<>(ResultType.NORMAL, cupBallGameService.getTotalGold());
    }

    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, CupBallGame entity) {
        if(null == entity || StringUtils.isBlank(entity.getGameDate())) {
            return new SerializeObjectError("25000004");
        }
        if (StringUtils.isBlank(entity.getGameTime())) {
            return new SerializeObjectError("25000005");
        }
        if (entity.getType() <= 0) {
            return new SerializeObjectError("25000006");
        }
        if (StringUtils.isBlank(entity.getTeamaId()) || StringUtils.isBlank(entity.getTeamaName())) {
            return new SerializeObjectError("25000007");
        }
        if (StringUtils.isBlank(entity.getTeambId()) || StringUtils.isBlank(entity.getTeambName())) {
            return new SerializeObjectError("25000008");
        }
        if (StringUtils.isNotBlank(entity.getResult())) {
            String[] infos = StringUtils.split(entity.getResult(), COLON);
            if (infos == null || infos.length != 2) {
                return new SerializeObjectError("25000009");
            }
            try {
                Integer.parseInt(infos[0]);
                Integer.parseInt(infos[1]);
            } catch (Exception e) {
                return new SerializeObjectError("25000009");
            }
        }
        if (cupBallGameService.save(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/guess")
    public SerializeObject guess(@RequestHeader String accessToken, String memberId, String gameId, int result) {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
        int currentDate = Integer.parseInt(format.format(Calendar.getInstance().getTime()));
        if (currentDate < properties.getStartDate()) {
            return new SerializeObjectError("25000010");
        }
        memberId = UF.toString(memberId);
        gameId = UF.toString(gameId);
        if(StringUtils.isBlank(memberId) || StringUtils.isBlank(gameId) || result < 1 || result > 3) {
            return new SerializeObjectError("00000002");
        }
        SerializeObject<MemberUserBean> userBean = memberUserService.findById(memberId);
        if (userBean == null || userBean.getData() == null) {
            return new SerializeObjectError("00000002");
        }
        CupBallGame game = cupBallGameService.getGame(gameId);
        if (game == null) {
            return new SerializeObjectError("00000002");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar startCalendar = Calendar.getInstance();
        Date startDate = null;
        try {
            startDate = dateFormat.parse(game.getGameDate() + " " + game.getGameTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        startCalendar.setTime(startDate);
        startCalendar.add(Calendar.MINUTE, -30);
        Calendar currentCalendar = Calendar.getInstance();
        if (currentCalendar.after(startCalendar)) {
            return new SerializeObjectError("25000013");
        }
        currentDate += 2;
        int start = Integer.parseInt(StringUtils.replaceAll(game.getGameDate(), "-", ""));
        if (start >= currentDate) {
            return new SerializeObjectError("25000010");
        }
        CupGuessUserBean guessUserBean = cupGuessUserService.getGuessUser(memberId, gameId);
        if (guessUserBean != null) {
            return new SerializeObjectError("25000011");
        }
        CupJoinUser cupJoinUser = cupJoinUserService.getJoinUser(memberId);
        if (cupJoinUser ==null || cupJoinUser.getBalance() < 1) {
            return new SerializeObjectError("25000012");
        }
        CupGuessUser guessUser = new CupGuessUser();
        guessUser.setGuessResult(result);
        guessUser.setGameId(gameId);
        guessUser.setMemberId(memberId);
        if (cupGuessUserService.save(guessUser)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.EXCEPTION, "00000005");
        }
    }

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<CupBallGame>> list(@RequestHeader String accessToken, Page page, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = cupBallGameService.count(startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<CupBallGame> list = cupBallGameService.query(startDate, endDate, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<CupBallGame>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<CupBallGame>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<CupBallGame>()));
    }

    @GetMapping(value = "/user/list")
    public SerializeObject<DataTable<CupGuessUserBean>> guessUserlist(@RequestHeader String accessToken, Page page, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = cupGuessUserService.count(startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<CupGuessUserBean> list = cupGuessUserService.list(startDate, endDate, offset, size);
            if (list != null && list.size() > 0) {
                for (CupGuessUserBean bean : list) {
                    if (StringUtils.isNotBlank(bean.getMobile())) {
                        bean.setMobile(StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMobile(), 7));
                    }
                }
            }
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<CupGuessUserBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<CupGuessUserBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<CupGuessUserBean>()));
    }

    @GetMapping(value = "/all/list")
    public SerializeObject<List<GameBean>> gameList(@RequestHeader String accessToken, String memberId) {
        memberId = UF.toString(memberId);
        return new SerializeObject<>(ResultType.NORMAL, cupBallGameService.listGames(memberId));
    }
}
